﻿using System.Globalization;
using System.Windows.Data;

namespace YY.Admin.Core.Converter
{
    /// <summary>
    /// 将枚举值和 bool 互转，适用于 ToggleButton 或 RadioButton
    /// </summary>
    public class EnumToBoolConverter : IValueConverter
    {
        /// <summary>
        /// 将枚举值转换为 bool
        /// </summary>
        /// <param name="value">绑定的枚举值</param>
        /// <param name="targetType"></param>
        /// <param name="parameter">ConverterParameter 指定要匹配的枚举值</param>
        /// <param name="culture"></param>
        /// <returns>匹配返回 true，否则 false</returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string enumValue = value?.ToString() ?? string.Empty;
            string targetValue = parameter?.ToString() ?? string.Empty;

            return enumValue.Equals(targetValue, StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 将 bool 转回枚举值
        /// </summary>
        /// <param name="value">ToggleButton.IsChecked</param>
        /// <param name="targetType"></param>
        /// <param name="parameter">ConverterParameter 指定对应的枚举值</param>
        /// <param name="culture"></param>
        /// <returns>如果 true 返回枚举，否则返回 Binding.DoNothing</returns>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool isChecked && isChecked && parameter != null)
            {
                return Enum.Parse(targetType, parameter.ToString()!);
            }
            return Binding.DoNothing;
        }
    }
}
